import 'package:dio/dio.dart';

class ErrorInterceptor extends Interceptor{
  final Dio dio;

  ErrorInterceptor(this.dio);

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async{
    switch(err.type){
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        //重试逻辑
        final request = err.requestOptions;
        final response = await _retry(request);
        return handler.resolve(response);
      case DioExceptionType.badResponse:
        if(err.response?.statusCode ==401){
          //Token过期处理
          return _handleTokenExpire(err,handler);
        }
        break;
      default:
        break;
    }
    return handler.next(err);
  }

  Future<Response> _retry(RequestOptions request) async{
    return dio.request(
      request.path,
      data: request.data,
      queryParameters: request.queryParameters,
      options: Options(
        method: request.method,
        headers: request.headers,
      )
    );
  }

  Future<void> _handleTokenExpire(
      DioException err,
      ErrorInterceptorHandler handler,
      ) async {
    try {
      // 1. 刷新token
      final newToken = await _refreshToken();

      // 2. 更新请求头
      final options = err.requestOptions;
      options.headers['Authorization'] = 'Bearer $newToken';

      // 3. 重新发送请求
      final response = await dio.fetch(options);
      return handler.resolve(response);
    } catch (e) {
      return handler.reject(err);
    }
  }

  Future<String> _refreshToken() async{
    // 实现token刷新逻辑
    return 'new_access_token';
  }
}